import log from "./logger";
import * as fs from 'fs';
import {spawnSync} from "child_process";
import {NodeCO, TrainAllCO} from "./interface";
import config from "./config";
import sender from "./sender";
import {axios, moment} from "../node-test";


function adjustEndDateTime(dateStr: string, startTimeStr: string, endTimeStr: string) {
    // 创建开始和结束的日期时间对象
    let startDateTime
    let startDateTimeFormatted
    let endDateTime
    let endDateTimeFormatted

    if (startTimeStr !== '') {
        startDateTime = moment(`${dateStr} ${startTimeStr}`, 'YYYY-MM-DD HH:mm:ss');
        startDateTimeFormatted = startDateTime.format('YYYY-MM-DD HH:mm:ss');
    } else {
        startDateTimeFormatted = ''
    }

    if (endTimeStr !== '') {
        endDateTime = moment(`${dateStr} ${endTimeStr}`, 'YYYY-MM-DD HH:mm:ss');
        endDateTimeFormatted = endDateTime.format('YYYY-MM-DD HH:mm:ss');
    } else {
        endDateTimeFormatted = ''
    }

    // 检查如果结束时间早于开始时间，将结束时间加一天
    if (startTimeStr !== '' && endTimeStr !== '' && endDateTime.isSameOrBefore(startDateTime)) {
        endDateTime.add(1, 'days');
        endDateTimeFormatted = endDateTime.format('YYYY-MM-DD HH:mm:ss');
    }
    return {
        startDateTime: startDateTimeFormatted,
        endDateTime: endDateTimeFormatted
    };
}

async function post2(dataStr: string) {
    const lines = dataStr.split(/\r?\n/);
    log.info('输出结果:', lines[0], lines[1]);
    const nodes: NodeCO[] = []
    if (lines.length < 3) {
        log.info("数据有问题")
        return;
    }
    for (let i = 1; i < lines.length - 1; i++) {
        const data = lines[i].split("|");
        // log.info(data);
        nodes.push({
            centerDeviation: "", frontBackDiff: "",
            diffWeight: Number.parseFloat(data[9]),
            code: lines[0].split("|")[1] + '-' + Number.parseInt(data[4]) + 1,
            lable: null,
            maxNetWeight: Number.parseFloat(data[7]),
            no: data[6],
            sort: Number.parseInt(data[4]) + 1,
            speed: null,
            standardTareWeight: null,
            time: data[11],
            trainCode: lines[0].split("|")[1],
            carType: data[5],
            weight: Number.parseFloat(data[8]),
            containerNumber1: null,
            containerNumber2: null,
            containerType1: null,
            containerType2: null,
            state: 'Done',
            createTenantId: null,
            createTenantName: null
        });
    }
    // 处理时间
    const ccsj = lines[0].split("|")[3];
    let start = lines[0].split("|")[4].trim();
    let end = lines[0].split("|")[5].trim();
    let adjustEndDateTime1 = adjustEndDateTime(ccsj, start, end);
    start = adjustEndDateTime1.startDateTime
    end = adjustEndDateTime1.endDateTime

    const trainCO: TrainAllCO = {
        boxCount: 0,
        code: lines[0].split("|")[1],
        deviceName: config.deviceName,
        direction: "Leave",
        endTime: end === '' ? lines[0].split("|")[11] : end,
        firstNo: nodes[0].no,
        lastNo: nodes[nodes.length - 1].no,
        name: lines[0].split("|")[2],
        no: lines[0].split("|")[2],
        nodes: nodes,
        platformId: config.platformId,
        platformName: config.platformName,
        productName: lines[0].split("|")[10],
        senderName: lines[1].split("|")[2],
        startTime: start === '' ? lines[0].split("|")[11] : start,
        stationName: lines[1].split("|")[3],
        time: lines[0].split("|")[11],
        totalDiffWeight: Number.parseFloat(lines[0].split("|")[9]),
        totalMaxWeight: Number.parseFloat(lines[0].split("|")[7]),
        totalNode: Number.parseInt(lines[0].split("|")[6]),
        totalWeight: Number.parseFloat(lines[0].split("|")[8]),
        type: "db",
        wagonType: "Gondola",
        createTenantId: null,
        createTenantName: null,
    };
    // log.info("trainCO:", trainCO);

    axios.post("https://platform.wechain360.com/api/depatch/internal/train/trainAll", trainCO).then((res: any) => {
        // log.info("send ok")
        if (res.data.code === '0000') {
        } else {
            log.error("send err data trainAll", trainCO)
            log.error("send err:", res.data.code, res.data.data)
        }
    }).catch((e) => {
        log.error("send err:", e.message)
    })

    try {
        await sender.send("trainAll", trainCO);
    } catch (e) {
        log.error("err:", e);
    }
}

class ZhangziTrainWorker {
    init() {
        this.collection();
        // setInterval(() => {
        //     this.collection();
        // }, 1000 * 60)
    }

    async collection() {
        try {
            // 源文件和目标文件的路径
            const sourcePath12 = '\\\\192.168.1.12\\tmhczcz\\Train.FDB';
            const targetPath12 = 'D:\\tmhczcz12\\Train.FDB';

            log.info(`开始复制文件：${sourcePath12} to ${targetPath12}`);
            fs.copyFileSync(sourcePath12, targetPath12);
            log.info(`复制文件完成`);

            log.info("开始执行数据采集，数据库路径：", targetPath12);
            const cmd1 = spawnSync('C:\\Users\\HUAWEI\\source\\repos\\firebirdReader\\firebirdReader\\bin\\x86\\Debug\\net8.0\\firebirdReader.exe', ["1", "1"], {encoding: 'utf8'});
            if (cmd1.stdout) {
                // log.info('输出结果:', cmd1.stdout);
                await post2(cmd1.stdout);
            }

            // 查看数据库是否有改变，update时间？hash？和现在的做比较，如果不一样则复制；
            // 源文件和目标文件的路径
            const sourcePath22 = '\\\\192.168.1.22\\tmhczcz\\Train.FDB';
            const targetPath22 = 'D:\\tmhczcz22\\Train.FDB';
            log.info(`开始复制文件：${sourcePath22} to ${targetPath22}`);
            fs.copyFileSync(sourcePath22, targetPath22);
            log.info(`复制文件完成`);
            log.info("开始执行数据采集，数据库路径：", targetPath22);
            const cmd2 = spawnSync('C:\\Users\\HUAWEI\\source\\repos\\firebirdReader\\firebirdReader\\bin\\x86\\Debug\\net8.0\\firebirdReader.exe', ["2", "1"], {encoding: 'utf8'});
            if (cmd2.stdout) {
                // log.info('输出结果:', cmd1.stdout);
                await post2(cmd2.stdout);
            }
        } catch (e) {
            log.error(e)
        }
        // 延时5分钟循环调用
        setTimeout(() => {
            log.info("延时时间到，开始新的采集")
            this.collection();
        }, 1000 * 60 * 5)
    }
}

const zhangziTrainWorker = new ZhangziTrainWorker();
export default zhangziTrainWorker;
//
// // 测试函数
// const date = "2023-04-01";
// const startTime = "22:16:24";
// const endTime = "00:06:46";
//
// const result = adjustEndDateTime(date, startTime, endTime);
// console.log(`开始时间: ${result.startDateTime}`);
// console.log(`结束时间: ${result.endDateTime}`);